package com.mybatis_puls.demo.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mybatis_puls.demo.entity.Approve;
import com.mybatis_puls.demo.entity.R;
import com.mybatis_puls.demo.entity.User;
import com.mybatis_puls.demo.service.ApproveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小🌤
 * @since 2020-12-19
 */
@RestController
@RequestMapping("/approve")
public class ApproveController {
    @Autowired
    private ApproveService approveService;


    /**
     * 保存
     * @param approve
     * @return
     */
    @GetMapping("/save")
    public Object save(Approve approve){
        boolean save = approveService.save(approve);
        String msg =save?"保存成功":"保存失败";
        return msg;
    }

    /**
     * 查询
     * @param userId
     * @return
     */
    @GetMapping("/info/{userId}")
    public Object info(@PathVariable("userId")Integer userId){
        QueryWrapper<Approve> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<Approve> list = approveService.list(wrapper);
        if(list.size()>0){
            return  list.get(0);
        }
        return new R().setCode(400);
    }

    /**
     * 修改
     * @param approve
     * @return
     */
    @GetMapping("/update")
    public Object update(Approve approve){
        approveService.updateById(approve);
        return approve;
    }



    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/updoladfile")
    public Object UPpload(MultipartFile file, Integer id) {
        String  newFileName=null;
        if (file != null) {
            String originalFilename = file.getOriginalFilename();
            // *只有当满足图片格式时才进来，重新赋图片名，防止出现名称重复的情况
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            newFileName = IdUtil.simpleUUID()+"."+fileSuffix;
            // 该方法返回的为当前项目的工作目录，即在哪个地方启动的java线程
            String dirPath = System.getProperty("user.dir");
            String path = File.separator + "src/main/resources/static/images/sfz/" + File.separator + newFileName;
            File destFile = new File(dirPath + path);
            newFileName="/images/sfz/"+newFileName;
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(destFile);
                // *将相对路径返回给前端
            } catch (IOException e) {
                return new R().setCode(400);
            }

        }

        return newFileName;
    }

}

